package com.union.vehicleassistant.module.setting;

import android.text.TextUtils;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.BusUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.clj.fastble.BleManager;
import com.clj.fastble.data.BleDevice;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hjq.language.LocaleContract;
import com.hjq.language.MultiLanguages;
import com.hjq.widget.layout.SettingView;
import com.union.vehicleassistant.R;
import com.union.vehicleassistant.action.DialogAction;
import com.union.vehicleassistant.adapter.PreSettingAdapter;
import com.union.vehicleassistant.aop.SingleClick;
import com.union.vehicleassistant.app.AppActivity;
import com.union.vehicleassistant.app.AppApplication;
import com.union.vehicleassistant.bean.ChannelBean;
import com.union.vehicleassistant.common.Constant;
import com.union.vehicleassistant.util.BlueToothUtil;
import com.union.vehicleassistant.util.DarkModeUtils;
import com.union.vehicleassistant.util.SettingUtils;
import com.union.vehicleassistant.widget.dialog.PreSettingDialog;
import com.union.vehicleassistant.widget.dialog.SelectDialog;

import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;

/**
 * 设置页面
 *
 * @author mz
 * @date-time 2025/1/9 18:19
 */
public class SettingActivity extends AppActivity implements DialogAction {

    private SettingView settingBle;
    private SettingView settingPressure;
    private SettingView settingTheme;
    private SettingView settingLanguage;
    private SettingView settingEcu;
    private RecyclerView rcvPreSetting;
    private PreSettingAdapter preSettingAdapter;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_setting;
    }

    @Override
    protected void initView() {

        settingBle = findViewById(R.id.setting_ble);
        settingPressure = findViewById(R.id.setting_pressure);
        settingTheme = findViewById(R.id.setting_theme);
        settingLanguage = findViewById(R.id.setting_language);
        settingEcu = findViewById(R.id.setting_ecu);
        rcvPreSetting = findViewById(R.id.rv_pre_setting);
        setOnClickListener(R.id.setting_ble, R.id.setting_pressure, R.id.setting_theme, R.id.setting_language, R.id.setting_ecu);

        updateThemeModeUI();

        Locale language = MultiLanguages.getAppLanguage(getContext());
        if (language.equals(LocaleContract.getSimplifiedChineseLocale())) {
            settingLanguage.setRightText(R.string.language_simple_chinese);
        } else if (language.equals(LocaleContract.getEnglishLocale())) {
            settingLanguage.setRightText(R.string.language_english);
        }

        settingPressure.setRightText(SettingUtils.getInstance().getPressureUnit());
    }

    private void refreshECUInfo() {
        String mac = SettingUtils.getInstance().getConnectBluetoothMac();
        if (TextUtils.isEmpty(mac)) {
            settingEcu.setRightText(R.string.ble_state_unconnected);
        } else {
            boolean connected = BleManager.getInstance().isConnected(mac);
            if (connected) {
                BleDevice bleDevice = BlueToothUtil.getBleDevice(mac);
                settingEcu.setRightText(bleDevice.getName());
            } else {
                settingEcu.setRightText(R.string.ble_state_unconnected);
            }
        }
    }

    @Override
    protected void initData() {

        List<ChannelBean> channels = generatePreSettingData();
        preSettingAdapter = new PreSettingAdapter(channels);
        rcvPreSetting.setAdapter(preSettingAdapter);

        preSettingAdapter.setOnItemClickListener(new OnItemClickListener() {
            @SingleClick
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                setChannelValue(position);
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        refreshECUInfo();
    }

    /**
     * 设置通道值
     *
     * @param position 选择的模式
     */
    private void setChannelValue(int position) {
        ChannelBean item = preSettingAdapter.getItem(position);
        new PreSettingDialog.Builder(this)
                .setPreSettingValue(item)
                .setListener((dialog, bean) -> {
                    List<ChannelBean> data = preSettingAdapter.getData();
                    data.get(position).setChannelOne(bean.getChannelOne())
                            .setChannelTwo(bean.getChannelTwo());
                    preSettingAdapter.notifyItemChanged(position);
                    SettingUtils.getInstance().setPreSettingData(data);
                }).show();
    }

    /**
     * 获取预设值
     *
     * @return 预设值list
     */
    private List<ChannelBean> generatePreSettingData() {
        String preSettingData = SettingUtils.getInstance().getPreSettingData();
        if (TextUtils.isEmpty(preSettingData)) {
            return null;
        }
        return new Gson().fromJson(preSettingData, new TypeToken<List<ChannelBean>>() {
        }.getType());
    }

    @SingleClick
    @Override
    public void onClick(View view) {
        super.onClick(view);
        int id = view.getId();
        if (id == R.id.setting_ble) {
            startActivity(BluetoothActivity.class);
        } else if (id == R.id.setting_pressure) {
            selectPressureUnit();
        } else if (id == R.id.setting_theme) {
            selectTheme();
        } else if (id == R.id.setting_language) {
            selectLanguage();
        }
    }

    /**
     * 选择压力单位
     */
    private void selectPressureUnit() {
        String unit = SettingUtils.getInstance().getPressureUnit();
        String[] unitArray = getResources().getStringArray(R.array.pressure_array);
        boolean useBar = unit.equalsIgnoreCase("bar");
        new SelectDialog.Builder(getContext())
                .setTitle(R.string.setting_pressure_unit)
                .setList(unitArray)
                .setSelect(useBar ? 1 : 0)
                .setSingleSelect()
                .setListener((dialog, data) -> {
                    Object[] objects = data.values().toArray();
                    Object object = objects[0];
                    if (object instanceof String) {
                        SettingUtils.getInstance().setPressureUnit((String) object);
                        settingPressure.setRightText((String) object);
                        if (!unit.equalsIgnoreCase((String) object)) {
                            BusUtils.post(Constant.BUS_UNIT_CHANGE);

                            preSettingAdapter.notifyDataSetChanged();
                        }
                    }
                }).show();
    }

    /**
     * 选择语言
     */
    private void selectLanguage() {
        String[] languageArr = getResources().getStringArray(R.array.language_array);
        Locale locale = MultiLanguages.getAppLanguage(getContext());
        boolean equals = MultiLanguages.equalsLanguage(LocaleContract.getEnglishLocale(), locale);
        new SelectDialog.Builder(getContext())
                .setTitle(R.string.language_select)
                .setSingleSelect()
                .setSelect(equals ? 1 : 0)
                .setList(languageArr)
                .setListener((dialog, data) -> {
                    boolean restart;
                    Iterator iterator = data.keySet().iterator();
                    if (iterator.hasNext()) {
                        Object next = iterator.next();
                        if (next instanceof Integer) {
                            if ((Integer) next == 0) {
                                restart = MultiLanguages.setAppLanguage(getContext(), LocaleContract.getSimplifiedChineseLocale());
                            } else {
                                restart = MultiLanguages.setAppLanguage(getContext(), LocaleContract.getEnglishLocale());
                            }

                            if (restart) {
                                postDelayed(AppApplication::restartApp, 200);
                            }
                        }
                    }
                }).show();
    }

    /**
     * 选择主题
     */
    private void selectTheme() {
        final List<SettingUtils.ThemeMode> themeModes = Arrays.asList(SettingUtils.ThemeMode.values());
        SettingUtils.ThemeMode selectedThemeMode = SettingUtils.getInstance().getThemeMode();
        final int selectedPos = themeModes.indexOf(selectedThemeMode);
        String[] themeArray = getResources().getStringArray(R.array.theme_array);
        new SelectDialog.Builder(getContext())
                .setSelect(selectedPos)
                .setSingleSelect()
                .setList(themeArray)
                .setListener((dialog, data) -> {
                    Object[] objects = data.keySet().toArray();
                    Object o = objects[0];
                    if (o instanceof Integer) {
                        SettingUtils.ThemeMode themeMode = themeModes.get((Integer) o);
                        SettingUtils.getInstance().setThemeMode(themeMode);
                        updateThemeModeUI();
                        postDelayed(AppApplication::restartApp, 200);
                    }
                }).show();
    }

    private void updateThemeModeUI() {
        final SettingUtils.ThemeMode themeMode = SettingUtils.getInstance().getThemeMode();
        String[] themeArray = getResources().getStringArray(R.array.theme_array);
        settingTheme.setRightText(themeArray[themeMode.value]);
    }

    @Override
    protected boolean isStatusBarDarkFont() {
        return !DarkModeUtils.isDarkMode(getContext());
    }
}
